package com.bjsxt.userscenter.common.util;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.mail.MailException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * spring发送邮件的工具类
 * @author hou
 *
 */
@Component("springEmailUtil")
public class SpringEmailUtil
{
	@Resource(name = "javaMailSenderImpl")
	private JavaMailSender javaMailSender;
	@Resource
	private SimpleMailMessage simpleMailMessage;
	/**
	 * 发送邮件
	 */
	public boolean sendMail(String to,String subject, String text)
	{
		try
		{
			this.simpleMailMessage.setTo(to);
			this.simpleMailMessage.setSubject(subject);
			this.simpleMailMessage.setText(text);
			this.javaMailSender.send(this.simpleMailMessage);
			return true;
		} catch (MailException e)
		{
			ConstatFinalUtil.LOGGER.info("---发送邮件失败----to:{},subject:{},text:{}-",
					to,subject,text,e);
		}
		
		return false;
		
	}
	/**
	 * 发送邮件解析HTML
	 */
	public boolean sendMailHtml(String to,String subject,String text)
	{
		try
		{
			MimeMessage message = this.javaMailSender.createMimeMessage();
			//true：表示发送的邮件是富文件，附件
			//设置编码
			MimeMessageHelper helper = new MimeMessageHelper(message, true,"UTF-8");
			//设置邮件的相关信息
			helper.setFrom(this.simpleMailMessage.getFrom());
			helper.setTo(to);
			helper.setSubject(subject);
			//表示富文本
			helper.setText(text,true);
			this.javaMailSender.send(message);
			ConstatFinalUtil.LOGGER.info("---发送邮件成功----to:{},subject:{},text:{}-",
					to,subject,text);
			return true;
		} catch (MessagingException e)
		{
			ConstatFinalUtil.LOGGER.error("---发送邮件失败----to:{},subject:{},text:{}-",
					to,subject,text,e);
		}
		return false ;
	}
}
